<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'dd_user';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = array();
    /**
     * 根据用户的openid查询或者创建用户，返回创建的用户信息
     * @param type $openid
     */
    public static function getUser($openid, $token) {
        $user = static::firstOrCreate(['openid'=>$openid]);
        if (empty($user->regtime)) {
            $url = sprintf("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN ", $token, $openid);
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            $res = curl_exec($ch);
            curl_close($ch);
            $resObj = json_decode($res);
            if ($resObj->subscribe == 1) {
                $user->regtime = time();
                $user->nickname = $resObj->nickname;
                $user->headimgurl = $resObj->headimgurl;
                $user->qrcode = md5($openid);
                $user->save();
                return $user;
            } 
        }
        return $user;
    }
    
    public function strHeadImg() {
        return $this->headimgurl ? $this->headimgurl : asset('images/headimg.jpg');
    }
    
    /**
     * 通过code换取用户信息为用户注册
     * @param type $code
     * @param string $refperson 推荐用户的推广码
     */
    public static function regUser($code, $refperson='') {
        //换取access_token
        $appid          = env('WECHAT_APPID');
        $appsecret      = env('WECHAT_APPSECRET');
        $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $ch = curl_init($get_token_url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        $tres = curl_exec($ch);
        curl_close($ch);
        $token_res = json_decode($tres);
        if (!$token_res->openid) {
            return false;
        }
        //通过换取的access_token和openid换取用户信息        
        if(!empty($refperson)) {
            $uinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token_res->access_token}&openid={$token_res->openid}&lang=zh_CN";
            $ch = curl_init($uinfo_url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            $ures = curl_exec($ch);
            curl_close($ch);
            $uinfo_res = json_decode($ures);
            $user = static::firstOrCreate(['openid'=>$uinfo_res->openid]);
            //$us = new static();
            //$refinfo = $us->getRefId($refperson);
            if (empty($user->regtime)) {
                $user->regtime = time();
                $user->nickname = $uinfo_res->nickname;
                $user->headimgurl = $uinfo_res->headimgurl;
                $user->qrcode = md5($user->openid);
//				if(!empty($refinfo['pid']))
//				{
//					$user->pid = $refinfo['pid'];
//				}
//				if(!empty($refinfo['ppid']))
//				{
//					$user->ppid = $refinfo['ppid'];
//				}
                $user->save();
                return $user;
            }
//            if (empty($user->pid) && !empty($refinfo['pid'])) {
//                $user->pid = $refinfo['pid'];
//                $user->save();
//            }
//            if (empty($user->ppid) && !empty($refinfo['ppid'])) {
//                $user->ppid = $refinfo['ppid'];
//                $user->save();
//            }
        } else {
            $user = static::where('openid', $token_res->openid)->first();
        }
        return $user;
    }
    
    /**
     * 获取注册用户推荐人id
     * 
     */
    public function getRefId($refperson) {
        $pid = static::where('qrcode', $refperson)->first();
        $ppid = static::where('id', $pid->pid)->first();
        $res['pid']     = $pid ? $pid->id : "";
        $res['ppid']    = $ppid ? $ppid->id : "";
        return $res;
    }
    
    /**
     * 获取到我的上级代理
     */
    public function strPref() {
        if ($this->pid) {
            $user = static::find($this->pid);
            return $user->nickname;
        } else {
            return "没有上级代理";
        }
        
    }
    /**
     * 获取一级代理人数
     */
    public function strPrimAgency() {
        return static::where('pid', $this->id)->count();
    }
    
    /**
     * 获取二级代理人数
     * @return type
     */
    public function strSecondAgency() {
        return static::where('ppid', $this->id)->count();
    }
    
    /**
     * 返回推荐人
     */
    public function strTjr() {
        if($this->pid) {
            $tjr = static::find($this->pid);
            return $tjr->nickname;
        } else {
            return "没有推荐人";
        }
    }
    /**
     * 返回该人贡献
     */
    public function strGx() {
        $money = Account::where('offeruid', $this->id)->sum('money');
        return $money ? $money : '0.00';
    }
    
    /**
     * 个人总收益
     */
    public function strTotalMoney() {
        $money = Account::where('uid', $this->id)->where('status', 1)->sum('money');
        return $money ? $money : '0.00';
    }
    
    /**
     * 个人可提现金额
     */
    public function strWithDrawMoney() {
        $totalMoney = Account::where('uid', $this->id)->where('status', 1)->sum('money');
        $txmoney = Account::where('uid', $this->id)->where('status', 2)->whereIn('pushstatus', [1, 2])->sum('money');
        return sprintf('%0.2f',($totalMoney - $txmoney));
    }
    
    /**
     * 开户行类型
     */
    public function strBankType() {
        $bank = Bank::find($this->banktype);
        return $bank ? $bank->name : "不支持的银行";
    }
    
    /**
     * 注册时间
     */
    public function strRegTime() {
        return date("Y-m-d", $this->regtime);
    }
    /**
     * 身份证照片
     */
    public function strCard($type = 1) {
        if ($type == 1) {
            return $this->idfront ? asset($this->idfront) : asset('images/idfront.jpg');
        } elseif ($type == 2) {
            return $this->idback ? asset($this->idback) : asset('images/idback.jpg');
        }
    }
}
